<?php

class Ali_fuwuchuangm extends My_Model
{

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('alipay_utils');
    }

    /**
     * @see http://doc.open.alipay.com/doc2/apiDetail?apiId=862&docType=4
     * @see http://doc.open.alipay.com/doc2/detail?treeId=26&articleId=103293&docType=1
     * @param $method
     * @param $notify_url
     * @return array
     */
    private function getBasicParams($method, $notify_url = PAY_ALI_NOTIFY) {
        return array(
            "app_id" => PAY_ALI_APPID_FUWUCHUANG,
            "method" => $method,
            "charset" => "utf-8",
            "sign_type" => "RSA",
            "timestamp" => date("Y-m-d H:i:s"),
            "version" => "1.0",
            "notify_url" => $notify_url,
            "biz_content" => array(),
        );
    }
    

    protected function reqAliApi($method, $data, $notify_url = PAY_ALI_NOTIFY) {
        $basic_param = $this->getBasicParams($method, $notify_url);
        $params = $basic_param;
        $params['biz_content'] = json_encode($data, JSON_UNESCAPED_UNICODE);

        //对待签名参数数组排序
        $pre_str = getSignContent($params);
//        var_dump($pre_str);exit();
        $my_sign = rsaSign($pre_str, PAY_ALI_QY_PRIVATE_KEY);
        $params["sign"] = $my_sign;

        $post_data = http_build_query ( $params );
// 		print_r($post_data);exit();
        $opts = array (
            'http' => array (
                'method' => 'POST',
                'header' => 'Content-type: application/x-www-form-urlencoded;charset=UTF-8',
                'content' => $post_data
            )
        );
        $context = stream_context_create ( $opts );
        $result = file_get_contents ( PAY_ALI_GATEWAY_FUWUCHUANG, false, $context );

        return $result;
    }

    // 生成支付宝预付款订单二维码
    public function genAliPrepayQRData($order_id, $subject, $body, $price,$notify_url, $expire_min=0) {
        $expire_min = $expire_min ? $expire_min : PAY_ALI_EXPIRE;
        $expire_time = date('Y-m-d H:i:s', time() + $expire_min * 60);
        $data = array(
            "out_trade_no" => $order_id,
            "total_amount" => $price,               // 预支付价格,单位:元
            "subject" => $subject,                  // 商品名称
            "body" => $body,                        // 商品详情
            "time_expire" => $expire_time           // 订单支付过期时间
        );
        $result = $this->reqAliApi('alipay.trade.precreate', $data,$notify_url);
        $req_arr = json_decode($result, 1);
        if ($req_arr["alipay_trade_precreate_response"]["code"] == 10000 &&
            $req_arr["alipay_trade_precreate_response"]["out_trade_no"] == $order_id) {
            $pay_url = $req_arr["alipay_trade_precreate_response"]["qr_code"];
            if (!empty($pay_url)) {
                $uuid = uniqid();
                $date = date('Y-m-d');
                $save_fullpath = "/tmp/qy_qrcode/{$date}/{$uuid}.png";
                mkdir_recursive(dirname($save_fullpath), 0777);

                $this->load->helper('qrcode');
                QRcode::png($pay_url, $save_fullpath, QR_ECLEVEL_L, 10);

                $this->load->helper('upload');
                $result_upload = upload_file_alipic("dingdan/qrcode", $save_fullpath);

                unlink($save_fullpath);

                return array('qr_image'=>$result_upload["origin"],'pay_url'=>$pay_url);
            }
        }
        return array();
    }



    public function verifyGW($biz_content, $is_sign_success=false)
    {
        $xml = simplexml_load_string($biz_content);
//        print_r($xml);
        $EventType = ( string )$xml->EventType;
//        echo "#";echo $EventType;exit();
        $response_xml = "<success>false</success><error_code>VERIFY_FAILED</error_code><biz_content>" . getPublicKeyStr(PAY_ALI_PUBLIC_KEY) . "</biz_content>";
        if ($EventType == "verifygw" && $is_sign_success) {
            $response_xml = "<success>true</success><biz_content>" . getPublicKeyStr(PAY_ALI_QY_PUBLIC_KEY) . "</biz_content>";
        }
        $return_xml = signResponse($response_xml, PAY_ALI_INPUT_CHARSET, PAY_ALI_QY_PRIVATE_KEY);
        return $return_xml;
    }
}

